package edu.cs.usask.ca.silver.plugin.rcp.handlers.create;

import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.handlers.HandlerUtil;

import edu.cs.usask.ca.silver.businesslogic.ids.ModelProjectID;
import edu.cs.usask.ca.silver.plugin.rcp.Activator;
import edu.cs.usask.ca.silver.plugin.rcp.components.SilverNameEnums;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.create.CreateModelVersionDialog;
import edu.cs.usask.ca.silver.plugin.rcp.handlers.create.helper.CreateDataProcedures;
import edu.cs.usask.ca.silver.plugin.rcp.jobs.LoggerReportScheduler;
import edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer.ProjectViewI;

/**
 * TODO documentation
 * 
 * @author Yudi Xue <yudi.xue@usask.ca>
 * 
 */
public class CreateModelVersionHandler extends AbstractHandler {

	private static Logger logger = Logger.getLogger(CreateModelVersionHandler.class);
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		ProjectViewI view = (ProjectViewI) HandlerUtil
				.getActiveWorkbenchWindow(event).getActivePage()
				.findView(event.getParameter("projectviewid"));

		ModelProjectID selectedmodelProjectID = (ModelProjectID) view
				.getTreeSelectionAsSilverTreeObject().getSilverObjectId();

		CreateModelVersionDialog dialog = new CreateModelVersionDialog(
				Activator.getDefault().getWorkbench()
						.getActiveWorkbenchWindow().getShell(),
				selectedmodelProjectID);

		dialog.create();

		try {
			if (view.checkIfSelectedIsOfSpecifiedType(SilverNameEnums.ModelProjectID)) {

				if (dialog.open() == Window.OK) {
					CreateDataProcedures
							.createNewMvFromCreateMvDialogWithAModelProjectIdSelected(
									dialog, view.getAssociatedStorage());
					view.updateTree();
				}
			} else {
				MessageDialog
						.openConfirm(
								dialog.getShell(),
								"Please select a Model Project",
								"Please select a Model Project from project view in order to create a model version. You may have selected multiple elements from the tree.");
			}
		} catch (ClassNotFoundException e) {
			LoggerReportScheduler.scheduleErrorLogging(logger,"error while creating model version in rcp command handler", e);
		}

		return null;

	}

}
